{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true,
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "# 文件读取与异常"
   ]
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 打开文件"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "Python中打开文件直接使用open函数即可\n",
    "open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)\n",
    "\n",
    "参数解释如下\n",
    "\n",
    "    1：file: 必需，文件路径（相对或者绝对路径）。如果是linux环境，路径一般表示为'./data/file_name',如果是windows环境，一般表示为'.\\data\\file_name',因反斜杠\"\"在Python中被视为转义字符，为确保正确，应以原字符串的方式指定路径，即在开头的单引号前加上r。\n",
    "    2：mode: 可选，文件打开模式\n",
    "    3：buffering: 可选，设置缓冲\n",
    "    4：encoding: 可选，一般使用utf8\n",
    "    5：errors: 可选，报错级别\n",
    "    6：newline: 可选，区分换行符，如\\n,\\r\\n等\n",
    "    7：closefd: 可选，传入的file参数类型\n",
    "    8：opener: 可选，可以通过调用opener来自定义opener。（比如读取excel特化的引擎——openpyxl库）"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "文件操作完成后一定要关闭文件对象  对象名.close()"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a\n"
     ]
    }
   ],
   "source": [
    "#读取文件\n",
    "myfile=open(r'./data/hello.txt')\n",
    "data=myfile.read(1)\n",
    "print(data)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "b\n"
     ]
    }
   ],
   "source": [
    "data=myfile.read(1) #文件指针 向后移动\n",
    "print(data)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "cde\n"
     ]
    }
   ],
   "source": [
    "data=myfile.read(3)\n",
    "print(data)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "outputs": [],
   "source": [
    "myfile.close()"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 全读"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "abcdefg\n"
     ]
    }
   ],
   "source": [
    "file2=open(r\"./data/hello.txt\")\n",
    "data2=file2.read()\n",
    "print(data2)\n",
    "file2.close()"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "abcdefg\n"
     ]
    }
   ],
   "source": [
    "#我们引入with关键字\n",
    "with open(r\"./data/hello.txt\") as myfile:\n",
    "    print(myfile.read())"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "abcdefg\n",
      "\n",
      "hjgklmn\n",
      "\n",
      "opqrst\n",
      "\n",
      "uvwxyz\n"
     ]
    }
   ],
   "source": [
    "#逐行读取\n",
    "with open(r\"./data/hello.txt\") as myfile:\n",
    "    for line in myfile:\n",
    "        print(line)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'list'>\n",
      "abcdefg\n",
      "hjgklmn\n",
      "opqrst\n",
      "uvwxyz\n"
     ]
    }
   ],
   "source": [
    "#也可以使用readlines方法  该方法返回一个列表\n",
    "with open(r\".\\data\\hello.txt\") as myfiles:\n",
    "    lists=myfiles.readlines()\n",
    "    print(type(lists))\n",
    "    for line in lists:\n",
    "        print(line.strip())"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 写入文件"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "outputs": [],
   "source": [
    "with open(r\"./data/new.txt\",'a') as myfile:\n",
    "    myfile.write(\"你好\")\n",
    "    myfile.close()"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "你好\n"
     ]
    }
   ],
   "source": [
    "#逐行读取\n",
    "with open(r\"./data/new.txt\") as myfile:\n",
    "    for line in myfile:\n",
    "        print(line)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "outputs": [],
   "source": [
    "#但是打开文件后显示是乱码 这是因为编码问题\n",
    "with open(r'.\\data\\newfile-utf8','a',encoding='utf-8') as myfile:\n",
    "   seq1 = [\"第一行\\n\",\"第二行\\n\"]\n",
    "   seq2 = (\"第三行\\n\",\"第四行\\n\")\n",
    "   myfile.writelines(seq1)\n",
    "   myfile.writelines(seq2)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 路径分为相对、绝对两种 不做赘述"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 扩展：OS库"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "H:\\LYX-Python\\Python基础\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "#获取当前路径\n",
    "curPath=os.path.abspath(os.path.curdir)\n",
    "print(curPath)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "outputs": [
    {
     "data": {
      "text/plain": "True"
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#判断指定文件是否存在\n",
    "path=\"./data/hello.txt\"\n",
    "os.path.exists(path)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "outputs": [
    {
     "data": {
      "text/plain": "True"
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#判断是否为文件\n",
    "os.path.isfile(path)  #True"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "outputs": [
    {
     "data": {
      "text/plain": "False"
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#判断是否为路径\n",
    "os.path.isdir(path)  #False"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}